//
//  BRMenuViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/9/27.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRMenuViewController.h"
#import "AppDelegate.h"
#import "BRInfoViewController.h"
#import "BROrederListViewController.h"
#import "BRSettingViewController.h"
#import "BRFAQListViewController.h"
#import "BRWalletViewController.h"
#import "BRMenuTableViewCell.h"
#import "BRInviteViewController.h"
#import "BRCouponsListViewController.h"
#import "BRPointsVC.h"
#import "BRMerchantVC.h"
#import "BRDevicePopupViewController.h"

#import "UIViewController+CWLateralSlide.h"

#define kMenuWidth (320)

@interface BRMenuViewController ()<QMUITableViewDelegate,QMUITableViewDataSource>
{
    UIView *_menuView;
    UIImageView *_headImg;
    QMUILabel *_nameLB;
    UIView *_tView;
    
}

@property (nonatomic,strong) NSArray *menuList;

@property (nonatomic,strong) NSDictionary *shopDic;

@end

@implementation BRMenuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self br_resetMenuListArr];
    [self setUI];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self setInfo];
}

- (void)dealloc {
    [kNotifyCenter removeObserver:self];
}

#pragma mark - Action --
- (void)hidden {
    
    [self hidden:0.25];
   
}

- (void)hidden:(CGFloat)time {
    
    [UIView animateWithDuration:time animations:^{
        self->_menuView.transform = CGAffineTransformMakeRotation(0);
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.view.hidden = YES;
    });
   
}

- (void)show {
    
//    [self setInfo];
    
    self.view.hidden = NO;
    [UIView animateWithDuration:0.25 animations:^{
        self->_menuView.transform = CGAffineTransformMakeTranslation(kMenuWidth, 0);
    }];
}

- (void)setInfo {
    // 使用用户ID，与个人中心页面保持一致
    _nameLB.text = [self br_getUserId];
}

- (void)setInfoLogo {
//    NSString *iconUrlStr = [NSString stringWithFormat:@"%@%@",USERManager.filesSever,USERManager.tenantModel.logo];
//    if (iconUrlStr.length != 0) {
//        [_headImg sd_setImageWithURL:[NSURL URLWithString:iconUrlStr] placeholderImage:UIImageMake(kDefaultSqureImg)];
//    }
}

- (void)logout {
    
    BRCustiomAlertView *alertV = [[BRCustiomAlertView alloc] initWithTitle:Localized(@"set_logout") subTitle:Localized(@"set_comfirmLogout") cancelAction:^{
        NSLog(@"取消");
        
    } successAction:^{
        NSLog(@"确定");
        [self logoutSucc];
    } showBC:YES];
    
    [self.view addSubview:alertV];
}

- (void)logoutSucc {
    [[BRUserManager share] logout:^{
        AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [app didInitWindow];
    } faile:^{
        AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [app didInitWindow];
    }];
}

- (void)toInfo  {
    BRInfoViewController *vc  = [[BRInfoViewController alloc] init];
    [self cw_pushViewController:vc];
   
}

- (void)backTap:(UISwipeGestureRecognizer *)swipe {
    
    if (swipe.direction == UISwipeGestureRecognizerDirectionLeft) {
        NSLog(@"隐藏");
        [self hidden];
    }
}

- (void)toTenantList {

}

- (void)changeEffect{
    
}

- (void)br_resetMenuListArr {
    
    
//    if (USERManager.userModel.isBranch) {
//        
//        self.menuList = [self.menuList arrayByAddingObjectsFromArray:@[@{@"title":Localized(@"menu_merchantCenter"),@"type":@"8"}]];
//        
//    }
}


#pragma mark - tableView Delegate --
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    

    return 56;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    BOOL isBranch = BRUserManager.share.userModel.isBranch;
    if (isBranch) {
        return self.menuList.count + 1;
    }
    return self.menuList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BRMenuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BRMenuTableViewCell"];
    NSDictionary *dic = @{};
    BOOL isBranch = BRUserManager.share.userModel.isBranch;
    if (isBranch && indexPath.row == self.menuList.count) {
        dic = self.shopDic;
    }else {
        dic = self.menuList[indexPath.row];
    }
    cell.menuTitle.text = dic[@"title"];
    NSInteger type = [dic[@"type"] integerValue];
    cell.typeImg.image = [self cellTypeImg:type];

    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BRMenuTableViewCell *cell = (BRMenuTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    NSString *title = cell.menuTitle.text;

    kNotiPost(kNotiResetHomeRadius, nil);
    
    if ([title isEqualToString:Localized(@"menu_orderRecord")]) {
        BROrederListViewController *vc = [[BROrederListViewController alloc] init];
        [self cw_pushViewController:vc];
        return;
    }
    
    // TODO: 暂时注释掉钱包功能，后续版本恢复
    // if ([title isEqualToString:Localized(@"menu_wallet")]) {
    //     BRWalletViewController *vc = [[BRWalletViewController alloc] init];
    //     
    //     [self cw_pushViewController:vc];
    //     return;
    // }
    
    if ([title isEqualToString:Localized(@"menu_setting")]) {
        BRSettingViewController *vc = [[BRSettingViewController alloc] init];
        [self cw_pushViewController:vc];
        return;
    }
    if ([title isEqualToString:Localized(@"menu_helpCentre")]) {
        BRFAQListViewController *vc = [[BRFAQListViewController alloc] init];
        [self cw_pushViewController:vc];
        return;
    }
    // TODO: 暂时注释掉优惠券功能，后续版本恢复
    // if ([title isEqualToString:Localized(@"menu_coupon")]) {
    //     BRCouponsListViewController *vc = [[BRCouponsListViewController alloc] init];
    //     [self cw_pushViewController:vc];
    //
    //     return;
    // }
    // TODO: 暂时注释掉积分功能，后续版本恢复
    // if ([title isEqualToString:Localized(@"menu_points")]) {
    //     BRPointsVC *vc = [[BRPointsVC alloc] init];
    //     [self cw_pushViewController:vc];
    //     return;
    // }
    // TODO: 暂时注释掉邀请功能，后续版本恢复
    // if ([title isEqualToString:Localized(@"menu_referral")]) {
    //     
    //     BRInviteViewController *vc = [[BRInviteViewController alloc] init];
    //     [self cw_pushViewController:vc];
    //     return;
    // }
  
    
    if ([title isEqualToString:Localized(@"shop_merchantCenter")]) {
        // 重置记录id
        USERManager.branchId = @"";
        BRMerchantVC *vc  = [[BRMerchantVC alloc] init];
        [self cw_pushViewController:vc];
        return;
    }
    
    // 测试弹宝
    // if ([title isEqualToString:@"测试弹宝"]) {
    //     BRDevicePopupViewController *vc = [[BRDevicePopupViewController alloc] init];
    //     vc.orderUuid = @"10006177";
    //     [self cw_pushViewController:vc];
    //     return;
    // }
    
}

- (UIImage *)cellTypeImg:(NSInteger)type {
    
    NSString *imgStr = [NSString stringWithFormat:@"menu_type%ld",type];

    return UIImageMake(imgStr);
    
}

#pragma mark - SET UI --
- (void)setUI {
    self.view.backgroundColor = UIColorClear;
    
    _menuView = [[UIView alloc] init];
    _menuView.backgroundColor = UIColorClear;
    [self.view addSubview:_menuView];
    [_menuView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.top.equalTo(self.view);
//        make.width.mas_equalTo(kScreenWidth);
        make.left.right.offset(0);
    }];
    
    CGFloat top_y = 150 +  KStatusBarHeight;
    
    CGFloat  head_y  = 30 + KStatusBarHeight;
    UIView *headView = [[UIView alloc] init];
    headView.backgroundColor = UIColorClear;
//    headView.layer.cornerRadius = 46.5;
//    headView.layer.masksToBounds = YES;
    [_menuView addSubview:headView];
    [headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(72);
        make.left.offset(20);
        make.top.offset(head_y);
    }];
    
    headView.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.12].CGColor;
    headView.layer.shadowOffset = CGSizeMake(4,6);
    headView.layer.shadowRadius = 16;
    headView.layer.shadowOpacity = 1;
    
    
    UIImageView *head = [[UIImageView alloc] init];
    
    // 使用新字段 avatar
    if (USERManager.userModel.avatar.length > 0) {
        // 如果有头像URL，使用SDWebImage加载
        NSString *fullAvatarUrl = [NSString stringWithFormat:@"%@%@", USERManager.filesSever ?: @"", USERManager.userModel.avatar];
        [head sd_setImageWithURL:[NSURL URLWithString:fullAvatarUrl] 
                placeholderImage:[self br_getDefaultAvatarImage]];
    } else {
        // 没有头像URL时使用默认头像
        head.image = [self br_getDefaultAvatarImage];
    }
    
    head.layer.cornerRadius = 36; // 圆形头像
    head.layer.masksToBounds = YES;
    [headView addSubview:head];
    [head mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.mas_equalTo(72);
        make.centerY.equalTo(headView.mas_centerY);
        make.centerX.equalTo(headView).offset(0);
    }];

    UIStackView *nameStack = [[UIStackView alloc] init];
    nameStack.axis = UILayoutConstraintAxisVertical;
    nameStack.spacing = 4;
    [_menuView addSubview:nameStack];
    [nameStack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(head.mas_right).offset(16);
        make.right.lessThanOrEqualTo(_menuView).offset(-8);
        make.centerY.equalTo(head.mas_centerY).offset(0);
    }];
    
    // 用户昵称/标签
    QMUILabel *nicknameLabel = [[QMUILabel alloc] init];
    nicknameLabel.text = [self br_getUserNickname];
    nicknameLabel.textColor = UIColor.qd_titleTextColor; // 黑色字体
    nicknameLabel.font = [UIFont br_fontS:17];
    nicknameLabel.numberOfLines = 2;
    [nameStack addArrangedSubview:nicknameLabel];
    
    // 用户编号
    QMUILabel *userNumberLabel = [[QMUILabel alloc] init];
    userNumberLabel.text = [self br_getUserNumber];
    userNumberLabel.textColor = UIColor.qd_titleTextColor; // 黑色字体
    userNumberLabel.font = [UIFont br_fontS:14];
    userNumberLabel.numberOfLines = 1;
    [nameStack addArrangedSubview:userNumberLabel];
    
    // 用户ID
    QMUILabel *userIdLabel = [[QMUILabel alloc] init];
    userIdLabel.text = [NSString stringWithFormat:@"ID: %@", [self br_getUserId]];
    userIdLabel.textColor = UIColor.qd_titleTextColor; // 黑色字体
    userIdLabel.font = [UIFont br_fontS:12];
    userIdLabel.numberOfLines = 1;
    [nameStack addArrangedSubview:userIdLabel];
    
    _nameLB = userIdLabel;
    _headImg = head;
    
    UIView *bgView = [UIView new];
    bgView.backgroundColor = UIColor.clearColor;
    [_menuView addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self->_menuView);
        make.top.offset(top_y);
    }];
    
    [bgView layoutIfNeeded];
 
    self.tableView.frame = CGRectMake(0, 34, kScreenWidth * 0.75, kScreenHeight );
    self.tableView.backgroundColor = UIColorClear;
    [bgView addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BRMenuTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"BRMenuTableViewCell"];
//    self.tableView.tableHeaderView = topImg;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(bgView);
        make.top.offset(0);
        make.bottom.offset(-(42 + kSafeAreaBottomHeight));//96
    }];
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, bgView.mj_w, 12)];
    headerView.backgroundColor = UIColorClear;
    
    
    self.tableView.tableHeaderView = headerView;
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, bgView.mj_w, 42)];
    bottomView.backgroundColor = UIColorClear;
    self.tableView.tableFooterView = bottomView;
    
    UIView *tView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, bgView.mj_w, 12)];
    tView.backgroundColor = UIColorClear;
    [bgView addSubview:tView];
    _tView = tView;
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    
    UITapGestureRecognizer *infoTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toInfo)];
    [headView addGestureRecognizer:infoTap];
    headView.userInteractionEnabled = YES;
    
//    NSString *version = [NSString stringWithFormat:@"%@: V %@",Localized(@"menu_version"),[BRTools getAppVersion]];
//    QMUILabel *versionL = [BRToolsView br_label:version textColor:kColorTitle font:[UIFont fontM:12] textAlignment:NSTextAlignmentCenter];
//    versionL.alpha = 0.4;
//    [self.view addSubview:versionL];
//    [versionL mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.offset(0);
//        make.bottom.offset(-(10 + kSafeAreaBottomHeight));
//    }];
    
    // ---侧边重影 ---
    CGFloat h = kScreenHeight * 0.66;
    CGFloat wR = kScreenWidth * 0.25;
    {
        UIImage *bubble = UIImageMake(@"menu_page2");
        UIImageView *bgV = [[UIImageView alloc] init];
        bgV.image = [bubble resizableImageWithCapInsets:UIEdgeInsetsMake(25, 0, 25, 0) resizingMode:UIImageResizingModeStretch];
        bgV.contentMode = UIViewContentModeScaleToFill;
        [self.view addSubview:bgV];
        [bgV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(h * 0.75);
            make.width.mas_equalTo(26);
            make.right.offset(-wR);
            make.centerY.offset(0);
        }];
    }
    UIImage *bubble = UIImageMake(@"menu_page1");
    UIImageView *bgV = [[UIImageView alloc] init];
    bgV.image = [bubble resizableImageWithCapInsets:UIEdgeInsetsMake(25, 0, 25, 0) resizingMode:UIImageResizingModeStretch];
    bgV.contentMode = UIViewContentModeScaleToFill;
    [self.view addSubview:bgV];
    [bgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(h * 0.85);
        make.width.mas_equalTo(16);
        make.right.offset(-wR);
        make.centerY.offset(0);
    }];
}

- (NSArray *)menuList {
    if (_menuList.count != 0) {
        return _menuList;
    }
    NSMutableArray *arr = [NSMutableArray arrayWithArray:@[
        
        @{@"title":Localized(@"menu_orderRecord"),@"type":@"1"},
        // TODO: 暂时注释掉钱包功能，后续版本恢复
        // @{@"title":Localized(@"menu_wallet"),@"type":@"2"},
        // TODO: 暂时注释掉优惠券功能，后续版本恢复
        // @{@"title":Localized(@"menu_coupon"),@"type":@"3"},
        // TODO: 暂时注释掉积分功能，后续版本恢复
        // @{@"title":Localized(@"menu_points"),@"type":@"4"},
        // TODO: 暂时注释掉邀请功能，后续版本恢复
        // @{@"title":Localized(@"menu_referral"),@"type":@"5"},
        @{@"title":Localized(@"menu_helpCentre"),@"type":@"6"},
        @{@"title":Localized(@"menu_setting"),@"type":@"7"},
        // TODO: 暂时注释掉测试弹宝功能，后续版本恢复
        // @{@"title":@"测试弹宝",@"type":@"99"}, // 测试弹宝功能
    ]];
    return arr;
    
}

- (NSDictionary *)shopDic {
    
    if (!_shopDic) {
        _shopDic = @{@"title":Localized(@"shop_merchantCenter"),@"type":@"8"};
    }
    return _shopDic;
}

- (UIImage *)br_getDefaultAvatarImage {
    // 使用系统默认的用户图标作为占位头像
    if (@available(iOS 13.0, *)) {
        UIImage *image = [UIImage systemImageNamed:@"person.circle.fill"];
        image = [image imageWithTintColor:UIColor.qd_titleTextColor renderingMode:UIImageRenderingModeAlwaysOriginal];
        return image;
    } else {
        // iOS 13以下使用默认图标
        return UIImageMake(@"AppLogo");
    }
}

#pragma mark - 用户信息获取 --
- (NSString *)br_getUserNickname {
    // 使用新字段 nickName
    if (USERManager.userModel.nickName.length > 0) {
        return USERManager.userModel.nickName;
    }
    return @"测试tag";
}

- (NSString *)br_getUserNumber {
    // 使用新字段 mobile
    if (USERManager.userModel.mobile.length > 0) {
        return USERManager.userModel.mobile;
    }
    return @"343710685";
}

- (NSString *)br_getUserId {
    // 使用新字段 userId 或 userID（映射自 JSON 的 id）
    NSString *userIdStr = USERManager.userModel.userId ?: USERManager.userModel.userID;
    if (userIdStr && userIdStr.length > 0) {
        return [NSString stringWithFormat:@"U%08ld", userIdStr.integerValue];
    }
    return @"U10000406";
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
